﻿using System;
using System.Text.RegularExpressions;
using Microsoft.Scripting;

namespace Cjc.Calculation.ExpressionEngine.Excel.Runtime.Types
{
	public struct CellId
	{
		private static Regex columnId = new Regex( @"([a-zA-Z]+)(?=[0-9]+)" );
		private static Regex rowId = new Regex( @"(?<=[a-zA-Z]*)([0-9]+)" );

		private int column;
		private int row;
		private SymbolId? symbol;

		public int Column { get { return column; } }
		public int Row { get { return row; } }

		public CellId( string id )
			: this(
				columnId.Match( id ).Groups[ 0 ].Value.ToUpper(),
				int.Parse( rowId.Match( id ).Groups[ 0 ].Value ) )
		{
			this.symbol = SymbolTable.StringToCaseInsensitiveId( id.ToUpper() );
		}

		public CellId( string columnId, int row )
			: this( columnId.ToUpper().FromBase26(), row )
		{
			this.symbol = null;
		}

		public CellId( int column, int row )
		{
			this.column = column;
			this.row = row;
			this.symbol = null;
		}

		public override string ToString()
		{
			return GetName( Column, Row );
		}

		public static string GetName( int column, int row )
		{
			return column.ToBase26() + row.ToString();
		}

		public static SymbolId GetSymbol( int column, int row )
		{
			return SymbolTable.StringToCaseInsensitiveId( GetName( column, row ) );
		}

		public SymbolId Symbol
		{
			get
			{
				if ( !symbol.HasValue ) symbol = GetSymbol( Column, Row );
				return symbol.Value;
			}
		}
	}
}